#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTextCodec>
#include <QSerialPort>
#include <QSerialPortInfo>
#include "comfun.h"
#include "protocol.h"

extern int protocol_handler(Ui::MainWindow *ui,unsigned char  data[],unsigned int data_len);
extern int send_frame(Ui::MainWindow *ui,uint8_t cmd,unsigned short did,uint8_t data[],int data_len );

uint8_t broadcast[ID_LEN] = {0xFF,0XFF,0XFF,0XFF};//
QSerialPort myserial;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QObject::connect(&myserial,&QSerialPort::readyRead,this,&MainWindow::on_serial_receive_data);
    on_pushButtonScan_clicked();
    ui->taid_lineEdit->setText(byte_num_to_hex_string_with_space(broadcast,ID_LEN));
}

MainWindow::~MainWindow()
{
    delete ui;
}

//串口接收数据槽函数
void MainWindow::on_serial_receive_data()
{
    QByteArray dataArray = myserial.readAll();//读取数据
    unsigned int data_len = dataArray.size();

    unsigned char *data_recv = new unsigned char [data_len];
    memcpy(data_recv,dataArray.data(),data_len);

    if(Qt::Checked == ui->checkBoxHexRece->checkState())//16进制显示
    {
        if(data_len !=0)//
        {
            QString str;
            str =  byte_num_to_hex_string_with_space(dataArray);
            ui->recvdata->insertPlainText(str);
        }
    }
    else
    {
        ui->recvdata->insertPlainText(dataArray);
    }

    int bytesCnt = ui->labelReceByteCnt->text().toInt();
    ui->labelReceByteCnt->setText(QString::number(bytesCnt+dataArray.size()));//接收字节数
    QTextCursor cursor=ui->recvdata->textCursor();
    cursor.movePosition(QTextCursor::End); //保持编辑器在光标最后一行
    ui->recvdata->setTextCursor(cursor);

    /**********************************/
    protocol_handler(ui,data_recv,data_len);

    delete[] data_recv;
}

void MainWindow::on_clearButton_clicked()
{
    ui->recvdata->setText("");
    ui->labelReceByteCnt->setText("0");
}

//数据发送
void MainWindow::on_pushButtonSend_clicked()
{
    char cunstom_buf[1024];
    if(myserial.isOpen())
    {
        if(ui->checkBoxHexSend->isChecked())//16进制发送
        {
            qDebug()<<"checkdatetype clicked";
            //将（16进制数）字符串转换成 unsigned char 数组  最大长度1024
            int cunstom_len = hex_str_to_byte_arr(ui->senddata->toPlainText(),
                                                  (uint8 *)cunstom_buf,
                                                  sizeof(cunstom_buf),true);
            if(cunstom_len<0)
                QMessageBox::information(this, tr("错误"), tr("16进制格式有误"));
            myserial.write(cunstom_buf);
        }
        else//字符串发送
        {
            myserial.write(ui->senddata->toPlainText().toUtf8());//字符发送
        }
    }
    else
    {
        QMessageBox::information(this, tr("提示"), tr("串口未打开！"));
    }

}

//扫描串口信道
void MainWindow::on_pushButtonScan_clicked()
{
    ui->comboBox_portName->clear();
    ui->recvdata->append("共扫描到 "
                              + QString::number(QSerialPortInfo::availablePorts().count())
                              + " 个可用串口：");


    foreach( const QSerialPortInfo &Info,QSerialPortInfo::availablePorts())//读取串口信息
    {
        qDebug() << "portName    :"  << Info.portName();//调试时可以看的串口信息
        qDebug() << "Description   :" << Info.description();
        qDebug() << "Manufacturer:" << Info.manufacturer();
        ui->recvdata->append(Info.portName() +"  "+ Info.description());
        QSerialPort serial;
        serial.setPort(Info);
        ui->comboBox_portName->addItem( Info.portName()  );//在comboBox那添加串口号
    }
}

void MainWindow::on_pushButtonOpenSerial_clicked()
{
    myserial.setPortName(ui->comboBox_portName->currentText());//combo中选定的串口号
    myserial.setBaudRate((ui->comboBoxBaud->currentText()).toInt());
    myserial.setDataBits((enum QSerialPort::DataBits)(ui->comboBoxDataBits->currentText().toInt()));
    /*停止位*/
    switch(ui->comboBoxStopBits->currentText().toInt())
    {
        case 1: myserial.setStopBits(QSerialPort::OneStop);break;
        case 3: myserial.setStopBits(QSerialPort::OneAndHalfStop);break;
        case 2: myserial.setStopBits(QSerialPort::TwoStop);break;
        default:qDebug()<<"停止位错误"; return;
    }
    /*奇偶校验*/
    switch(ui->comboBoxParity->currentIndex())
    {
        case 0: myserial.setParity(QSerialPort::NoParity);break;
        case 1: myserial.setParity(QSerialPort::OddParity);break;
        case 2: myserial.setParity(QSerialPort::EvenParity);break;
        default:qDebug()<<"校验位错误"; return;
    }

    myserial.setFlowControl(QSerialPort::NoFlowControl);//流控制

    if( myserial.isOpen() )
        myserial.close();
    else
        myserial.open(QIODevice::ReadWrite);//打开串口

    if( myserial.isOpen() )
    {
        ui->pushButtonOpenSerial->setIcon(QIcon(":/image/serial_opened_icon"));
        ui->pushButtonOpenSerial->setText("关闭串口");
        //ui->serial_setting->close();
    }
    else
    {
        ui->pushButtonOpenSerial->setIcon(QIcon(":/image/serial_closed_icon"));
        ui->pushButtonOpenSerial->setText("打开串口");
    }

    if(myserial.error())
    {
        QMessageBox::information(this, tr("提示"), tr("操作失败，请重试或者重启本软件！"));
        qDebug()<<"串口打开失败，原因是："<<myserial.error();
        myserial.clearError();
    }
}

//
void MainWindow::on_sample_button_clicked()
{
     int send_success = send_frame(ui,CMD_READ,GET_SENSOR,NULL,0);
     switch (send_success)
     {
          case -1:
                  QMessageBox::information(this, tr("提示"), tr("串口未打开！"));
                  break;
          case -2:
                  QMessageBox::information(this, tr("错误"), tr("TAID格式有误"));
                  break;
      }
      return ;
}


void MainWindow::on_ReadAddrButton_clicked()
{
    int send_success = send_frame(ui,CMD_READ,GET_DEVADDR,NULL,0);
    switch (send_success)
    {
        case -1:
                QMessageBox::information(this, tr("提示"), tr("串口未打开！"));
                break;
        case -2:
                QMessageBox::information(this, tr("错误"), tr("TAID格式有误"));
                break;
    }
    return ;
}

void MainWindow::on_readpara_button_clicked()
{
    int send_success = send_frame(ui,CMD_READ,GET_PARA,NULL,0);
    switch (send_success)
    {
        case -1:
                QMessageBox::information(this, tr("提示"), tr("串口未打开！"));
                break;
        case -2:
                QMessageBox::information(this, tr("错误"), tr("TAID格式有误"));
                break;
    }
    return ;
}

void MainWindow::on_ReadVerButton_clicked()
{
    int send_success = send_frame(ui,CMD_READ,GET_PROGRAME_VER,NULL,0);
    switch (send_success)
    {
        case -1:
                QMessageBox::information(this, tr("提示"), tr("串口未打开！"));
                break;
        case -2:
                QMessageBox::information(this, tr("错误"), tr("TAID格式有误"));
                break;
    }
    return ;
}

void MainWindow::on_SetAddrButton_clicked()
{
    uint8_t taid[ID_LEN];
    int cunstom_len = hex_str_to_byte_arr(ui->devID_lineEdit->text(),
                                          (uint8 *)taid,
                                          sizeof(taid),true);
    if(cunstom_len<4)
    {
        QMessageBox::information(this, tr("错误"), tr("TAID格式有误"));
        return ;
    }
    mem_reverse(taid,ID_LEN);//quxiaoduan
    send_frame(ui,CMD_SET,GET_DEVADDR,taid,ID_LEN);
}
